<template>
  <el-dialog v-model="model" @close="closedDialog">

    <el-form ref="applyTypeFormRef" :model="form" label-width="80px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="委派人" prop="selectedPerson">
            <DeptSelect v-model="form.selectedPerson" filterable clearable>
            </DeptSelect>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="候选人" prop="selectedPerson">
            <DeptSelect v-model="form.selectedCandidates" multiple filterable clearable>
            </DeptSelect>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer container">
        <el-button type="primary" @click="onPersonSelected">{{
          $t("common.confirm")
        }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeMount, watch, onMounted } from "vue";
import type { FlowAssignTaskRequest } from "@/api/flow/task/types";
import { taskApi } from "@/api/flow/task/index";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const props = defineProps({
  taskId: {
    type: String,
    default: "",
  },
  //分配的用户id(委托人)
  assigneeId: {
    type: String,
    default: "",
  }
});
const emits = defineEmits(["refresh"]);
let req: FlowAssignTaskRequest = {
  requestId: Math.random() * 10 + "",
  taskId: props.taskId,
};


const form = reactive({
  // 单选选中的人
  selectedPerson: props.assigneeId,
  //多选候选人
  selectedCandidates: [] as string[],
})


const onPersonSelected = () => {
  // 可以在此处添加逻辑处理选择人后的动作
  req.userId = form.selectedPerson;
  req.candidateUser = form.selectedCandidates;
  req.taskId = props.taskId;
  console.log(form.selectedPerson,form.selectedCandidates); 
  
  if((form.selectedPerson == undefined || form.selectedPerson == "" || form.selectedPerson == null) && form.selectedCandidates.length == 0){
    ElMessage({
      message: "委派人或者候选人,最少选择一位",
      type: "error",
    });
    return
  }
  taskApi.assignTask(req).then((res) => {
    if (res.status === 200) {
      ElMessage({
        message: t("common.submitSuccess"),
        type: "success",
      });
      emits("refresh", res.status === 200);
      model.value = false;
    }
  });
};

onMounted(async () => {
  const { data: { results } } = await taskApi.findTaskUser({
    taskId: props.taskId,
    type: "candidate"
  })
  form.selectedCandidates = results.map(item => item.userId) as string[]
})

const model = defineModel<boolean>();
// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}
</script>
